import { postEx,getEx,removeEx } from "./crud"
export function getDevRule(tid,alarmID){
    return new Promise((re,rej)=>{
        getEx("/alarm/cfg/rule/" + tid).then((res)=>{
            if(res && res.data && res.data.result){
                let result = res.data.result
                if(!result || !result.alarm_condition_rules){
                    re("")
                    return
                }
                let rules = result.alarm_condition_rules
                let rule = rules.find(r=>{
                    return r.tid === alarmID
                })
                re(rule ? rule.expression : "")
            }else{
                re("")
            }
        }).catch(err=>{
            rej(err)
        })
    })
}
export function refreshDevRule(tid,alarmList){
    return new Promise((re,rej)=>{
        getEx("/alarm/cfg/rule/" + tid).then((res)=>{
            if(res && res.data && res.data.result){
                let result = res.data.result
                if(!result || !result.alarm_condition_rules){
                    re()
                    return
                }
                alarmList.forEach(alarm => {
                    let ia = result.alarm_condition_rules.find(a=>{
                        return a.tid === alarm.identifier
                    })
                    if(ia){
                        alarm.dev_cfg = ia.expression
                    }else{
                        alarm.dev_cfg = ""
                    }
                    
                });
            }
            re()
        }).catch(()=>{
            rej()
        })
    })
    
}
export function saveDevRule(tid,rule){
    return postEx("alarm/cfg/rule/condition/" + tid,rule)
}
export function delDevRule(tid){
    return removeEx("/alarm/cfg/rule/"+tid)
}
export default{
    getDevRule,
    postEx,
    delDevRule,
}